package com.mi.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mi.entity.AdminEntity;
import com.mi.entity.ResponseMsg;
import com.mi.entity.RoleInfo;
import com.mi.service.AdminService;
import com.mi.service.RoleService;
import com.mi.util.MyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    RoleService roleService;

    //唯一校验
    @RequestMapping("/soleAdmin")
    @ResponseBody
    public ResponseMsg sole(AdminEntity adminEntity){
        AdminEntity adminEntity1 = adminService.soleAdmin(adminEntity);
        ResponseMsg responseMsg = new ResponseMsg();
        if(adminEntity1==null){
            responseMsg.setResult("0000");
        }else{
            responseMsg.setResult("0001");
        }
        return responseMsg;
    }

    //登录
    @RequestMapping("/login")
    public String login(AdminEntity adminEntity, HttpServletRequest request){
        if(adminEntity==null|| MyUtil.isEmpty(adminEntity.getAccount())||MyUtil.isEmpty(adminEntity.getApass())){
            return "login";
        }
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(adminEntity.getAccount(), DigestUtils.md5DigestAsHex(adminEntity.getApass().getBytes()));
        // 执行认证登陆
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            request.setAttribute("info","未知账户");
        } catch (ExcessiveAttemptsException eae) {
            request.setAttribute("info","用户名或密码错误次数过多");
        } catch (AuthenticationException ae) {
            request.setAttribute("info","用户名或密码不正确！");
        }
        if (subject.isAuthenticated()) {
            AdminEntity login = adminService.login(adminEntity);
            request.getSession().setAttribute("admin",login);
            return "redirect:index";
        }
        token.clear();
        return "login";
    }

    //跳转到welcome
    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }

    //跳转到主页
    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    //没有权限界面
    @RequestMapping("/notRole")
    public void notRole(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<h1>你没有访问该页面的权限，请联系管理员。。。</h1>");
    }

    //根据条件查询管理员列表
    @RequestMapping("/adminList")
    public String adminList(HttpServletRequest req ,AdminEntity adminEntity){
        PageHelper.startPage(adminEntity.getPageNum(),adminEntity.getPageSize());
        List<AdminEntity> adminPojos = adminService.queryAdmin(adminEntity);
        PageInfo<AdminEntity> list = new PageInfo<>(adminPojos);
        req.setAttribute("aname",adminEntity.getAname());
        req.setAttribute("account",adminEntity.getAccount());
        req.setAttribute("pageInfo",list);
        return "adminList";
    }

    //根据一组id删除管理员
    @RequestMapping("/delAdmins")
    @ResponseBody
    public ResponseMsg delAdmins(String ids){
        ResponseMsg responseMsg = new ResponseMsg();
        if(ids == null||"".equals(ids)){
            responseMsg.setResult("0001");
            responseMsg.setResultMsg("删除失败");
        }else{
            String[] aids;
            if (ids.contains(",")) {
                aids = ids.split(",");
            } else {
                aids = new String[]{ids};
            }
            boolean b = adminService.delAdmin(aids);
            if (b) {
                responseMsg.setResult("0000");
            } else {
                responseMsg.setResult("0001");
                responseMsg.setResultMsg("删除失败");
            }
        }
        return responseMsg;
    }

    //转发到添加管理员界面
    @RequestMapping("/adminAdd")
    public String adminAdd(HttpServletRequest req){
        List<RoleInfo> rolePojos = roleService.queryAllRole(new RoleInfo());
        req.setAttribute("roles",rolePojos);
        return "adminAdd";
    }

    //添加管理员
    @RequestMapping("/addAdmin")
    @ResponseBody
    public ResponseMsg addAdmin(AdminEntity adminEntity){
        ResponseMsg responseMsg = new ResponseMsg();
        adminEntity.setApass(DigestUtils.md5DigestAsHex(adminEntity.getApass().getBytes()));
        boolean b = adminService.addAdmin(adminEntity);
        if(b){
            responseMsg.setResult("0000");
        }else{
            responseMsg.setResult("0001");
            responseMsg.setResultMsg("添加失败");
        }
        return responseMsg;
    }

    //转发到修改管理员界面
    @RequestMapping("/adminEdit")
    public String adminEdit(HttpServletRequest req,int aid){
        List<RoleInfo> rolePojos = roleService.queryAllRole(new RoleInfo());
        AdminEntity adminInfo = new AdminEntity();
        adminInfo.setAid(aid);
        List<AdminEntity> adminEntities = adminService.queryAdmins(adminInfo);
        if (adminEntities!=null&&adminEntities.size()>0) {
            req.setAttribute("adminPojo", adminEntities.get(0));
            if(adminEntities.get(0).getRoless()!=null){
                for (int i = 0; i < adminEntities.get(0).getRoless().size(); i++) {
                    for (int j = 0; j < rolePojos.size(); j++) {
                        if(adminEntities.get(0).getRoless().get(i).getRid()==rolePojos.get(j).getRid()){
                            rolePojos.get(j).setRstatus(2);
                        }
                    }
                }
            }
            req.setAttribute("roles",rolePojos);
            return "adminEdit";
        }else{
            return "404";
        }
    }

    //修改管理员
    @RequestMapping("/updAdmin")
    @ResponseBody
    public ResponseMsg updAdmin( AdminEntity adminEntity){
        ResponseMsg responseMsg = new ResponseMsg();
        boolean b = false;
        try {
            b = adminService.updAdmin(adminEntity);
        } catch (Exception e) {
            e.printStackTrace();
            b = false;
        }finally {
            if(b){
                responseMsg.setResult("0000");
            }else{
                responseMsg.setResult("0001");
                responseMsg.setResultMsg("修改失败");
            }
            return responseMsg;
        }
    }

    //修改用户状态
    @RequestMapping("/updAdminStatus")
    @ResponseBody
    public ResponseMsg updAdminStatus(AdminEntity adminEntity){
        ResponseMsg responseMsg = new ResponseMsg();
        boolean b = false;
        try {
            b = adminService.updAdminStatus(adminEntity);
            if(b){
                responseMsg.setResult("0000");
            }else{
                responseMsg.setResult("0001");
                responseMsg.setResultMsg("修改失败");
            }
        } catch (Exception e) {
            responseMsg.setResult("0001");
            responseMsg.setResultMsg("修改失败");
        }finally {
            return responseMsg;
        }
    }

    //跳转修改密码
    @RequestMapping("/passwd")
    public String passwd(){
        return "passwd";
    }

    //修改密码
    @RequestMapping("/passEdit")
    @ResponseBody
    public ResponseMsg passEdit(String oldpass,String pass,HttpServletRequest request){
        ResponseMsg responseMsg = new ResponseMsg();
        if(pass==null||"".equals(pass)){
            responseMsg.setResult("0001");
            responseMsg.setResultMsg("修改失败");
            return responseMsg;
        }
        pass = DigestUtils.md5DigestAsHex(pass.getBytes());
        oldpass = DigestUtils.md5DigestAsHex(oldpass.getBytes());
        boolean b = false;
        try {
            Integer admin = ((AdminEntity) request.getSession().getAttribute("admin")).getAid();
            AdminEntity adminEntity = new AdminEntity();
            adminEntity.setAid(admin);
            adminEntity.setApass(pass);
            adminEntity.setAcreate(oldpass);
            b = adminService.updPass(adminEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(b){
                responseMsg.setResult("0000");
            }else{
                responseMsg.setResult("0001");
                responseMsg.setResultMsg("修改失败");
            }
            return responseMsg;
        }
    }
}
